package com.qg.auth.interceptor;

import com.qg.auth.handler.WebContext;
import com.qg.auth.properties.QgAuthProperties;
import com.qg.auth.util.WebContextUtil;
import com.qg.base.constants.WebConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author QG
 * @Date 2023/5/25 15:53
 * @description 登录拦截器
 **/
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private QgAuthProperties qgAuthProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //将请求和回复放入上下文，用于后续处理
        WebContext.setRequest(request);
        WebContext.setResponse(response);
        //需要放行的路径放行
        if(!qgAuthProperties.getEnable()) {
            return true;
        }
        String requestURI = request.getRequestURI().replace(request.getContextPath(), "");
        String[] split = qgAuthProperties.getLoginUri().split(",");
        for (int i = 0; i < split.length; i++) {
            if(requestURI.equals(split[i])) {
                //放行
                return true;
            }
        }
        //认证
        //获取用户信息，进行认证等判断
        Map user = WebContextUtil.getUserInfo();
        if(user == null) {
            return false;
        }
        //将用户信息放入request中，通过request.getAttribute()获取用户信息
        request.setAttribute(WebConstant.USER,user);
        return true;
    }
}
